$(function(){


    $(".buy").each(function (i, element){
        if(!Number($(".inventory:eq("+i+")").html()) > 0){
            $(this).attr("disabled",true);
        }
    });

    countdown.setLabels(
            ' 毫秒| 秒| 分| 小时| 天| 周| 月| year| decade| century| millennium',
            ' 毫秒| 秒| 分| 小时| 天| 周| 月| year| decade| century| millennium',
            '',
            null,
            '0');



    var timer = setInterval(function(){
        $(".countdown").each(function (i, element){
            end = moment($(".end_time:eq("+i+")").html(), "YYYY-MM-DD HH:mm:ss");
            start = moment($(".start_time:eq("+i+")").html(), "YYYY-MM-DD HH:mm:ss");
            now = moment();
            if(start.unix() > now.unix()){
                $(".countdown:eq("+i+")").html("<strong>待开始</strong>");
                $(".easyui-numberspinner:eq("+i+")").numberspinner({
                    disabled: true
                });
                var itemid = $(".itemid:eq("+i+")").html();
                $("#buy"+itemid).attr("disabled",true);
            }
            else{
                $(".countdown:eq("+i+")").html("<strong>还剩\t</strong>"+countdown(moment(), end).toHTML("strong"));
                if (moment() >= end){
                    // clearInterval(timer);
                    $(".countdown:eq("+i+")").html("<strong>已结束</strong>")
                    $(".easyui-numberspinner:eq("+i+")").numberspinner({
                        disabled: true
                    });
                    var itemid = $(".itemid:eq("+i+")").html();
                    $("#buy"+itemid).attr("disabled",true);
                }
            }
        })},
        1000);

    $('.buy').click(function(event) {
        var i = $('.buy').index(this);
        var itemid = $(".itemid:eq("+i+")").html();
        var title = $(".item_title:eq("+i+")").html();
        var quantity = $(".easyui-numberspinner:eq("+i+")").numberspinner('getValue');
        $.post('/holdItem',{'itemid':itemid, 'quantity':quantity, 'openid':$.cookie('openid')}, function(data, status){
            if(data.result){
                url = 'http://'+window.location.host+'/addr';
                url += '?id='+itemid;
                url += '&quantity='+quantity;
                url += '&task_id='+data.result;
                window.location.href = url;
            }
            else{
                sweetAlert("已售罄", "等等看也许有机会", "error");
            }
        });
    });

    function reAuth(){
        swal({ title: "微信授权中...", timer: 2000, showConfirmButton: false });
        setTimeout(function(){
            url = encodeURIComponent('http://'+window.location.host+window.location.pathname);
            redirectUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5bf47679c84ef3c8&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
            window.location.href = redirectUrl;
        }, 2000);

    }
});

